var app = getApp();
import {
  api,
  util, 
  dialog,
  clickIncrement,
  clearIncrement,
  forms,
  storage
} from '../../../js/util'
import {
  router
} from '../../../js/router'
import {
  fastorder,
  order,
  cart
} from "../../../js/modules/order.js"
import {
  detail,
  mall,
  list,
  scant
} from "../../../js/modules/mall.js";
import {
  activities
} from '../../../js/modules/market';
import {
  area,config
} from '../../../js/modules/gloab';
import {
  GoodsNumCache
} from '../../../js/modules/propertycache.js'
import {
  upload
} from '../../../js/modules/material.js'
import authorize from '../../../js/modules/authorize'
import { theme } from '../../../js/modules/theme'
import BasePage from '../../../js/common/base-page'
import { hideTabbar } from '../../../js/compatible';
BasePage({
  pageKey: "category",
  validateLogin: app.dns.fkId != app.dns.proprietorId,
  /**
   * 页面的初始数据
   */
  data: { 
    imgDomain: api.imgDomain,
    enableOss: api.enableOss,
    // allTabList:['目录', '收藏', '常购', '复购', '扫码', '拍照'],
    // tablist: [],
    activeIndex: 0,
    // sliderOffset: 0,
    // sliderLeft: 10,
    // slidewidth: 0,
    lists: [{
        activeIndex: 0,
        pageKey: "category",
        time:null,
        list: [],
        hasMoreData: true,
        page: {
          PageIndex: 1,
          PageSize: 20,
          keywords: ""
        }
      },
      {
        activeIndex: 1,
        pageKey: "favorite",
        time: null,
        list: [],
        hasMoreData: true,
        page: {
          PageIndex: 1,
          PageSize: 20,
          keywords: ""
        }
      },
      {
        activeIndex: 2,
        pageKey: "offenBuy",
        time: null,
        list: [],
        hasMoreData: true,
        page: {
          PageIndex: 1,
          PageSize: 20,
          keywords: "",
          sortField: "",
          sortDirect: ""
        }
      },
      {
        activeIndex: 3,
        pageKey: "repurchase",
        list: [],
        hasMoreData: true,
        page: {
          PageIndex: 1,
          PageSize: 20,
          keywords: "",
          sortField: "",
          sortDirect: "desc"
        }
      },
      {
        activeIndex: 4,
        pageKey: "scan",
      },
      {
        activeIndex: 5,
        pageKey: "takePhoto",
      }
    ],
    choosePanicbuy: [],
    chooseGoodsArray: [],
    chooseGoodsSpec: [],
    chooseGoodsUnits: [],
    code: "",
    isPanic: false,
    isScanty: false,
    quantityDigits: 0,
    priceDigits:2,
    decimalDigits:2,
    spectStyle:0,
    scantyProduct: [],
    is_search:false,
    tabKey: "product_" + app.dns.proprietorId,
    isAginBuying:false,
    isLogin: authorize.isLogin(),
    photolist:[],
    virtualImageList:[],
    loopCount:0,
    visitTimer:null,
    goods:[],//
    Currency:'',//货币符号
    tabindex:-1,
    GoodsUnitDisplayMode:0,
    FrontShowStockDetail:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    console.log(options.good,'----goods');
    that.setData({
      goods:JSON.parse(options.good),
    })
    app.initTabBar();
    that.productlist = that.selectComponent("#productlist");
    that.fasterComponent = that.selectComponent("#fasterComponent");
    that.outofstock = that.selectComponent("#outofstock");
    //this.wireshark = this.selectComponent("#wireshark");
    that.deliveryComponent = that.selectComponent("#deliveryComponent");

  },

  /**
   * 加载列表 
   * */
  loadList() {
    var that = this;
    let { activeIndex, lists } = this.data;
    let current = lists[activeIndex];
    if (current == null || current == undefined) return;  
    let list_key = "lists[" + activeIndex + "].list";
    let list_has = "lists[" + activeIndex + "].hasMoreData";
    let list_time = "lists[" + activeIndex + "].time";
    let isLoadComplete = "lists[" + activeIndex + "].isLoadComplete";
    //没有登录不显示数据
    if (!authorize.isLogin("store")) {
      that.setData({
        [list_key]:[],
        [isLoadComplete]: true
      });
      return;
    }

  
    var entity = authorize.getEntity();
    let areaCode = area.getCacheLocation().Code;
    this.data.areaCode = areaCode;
    let param = Object.assign({ areaCode: areaCode}, current.page);
    fastorder.loadList(activeIndex, param, function(content) {
      var hasMoreData = content.count > (current.page.PageIndex) * current.page.PageSize;

      var index = lists[activeIndex].list.length;
      var data = content.data || [];
      // add a judge by xp
      if (current && current.page) {
        //当分页大于1时，累加
        if (current.page.PageIndex > 1) {
          data = lists[activeIndex].list.concat(data);
        }
      }

      //如果key为变量作为key值的时候要用[]包裹起来
      that.setData({
        [list_time]:new Date().getTime(),
        [list_key]: data,
        [list_has]: hasMoreData,
        [isLoadComplete]: true
      },function(){
        if (content.data == undefined || activeIndex == 3) return;
        //加载商品活动信息
        activities.loadProductActivities(content.data,false,0,areaCode,function(goodslist, index) {
          var len = lists[activeIndex].list.length;
          for (var i = 0; i < goodslist.length && index + i < len; i++) {
            lists[activeIndex].list[index + i] = goodslist[i];
          }
          that.setData({
            [list_key]: lists[activeIndex].list,
          });
        }, index);
      });
    });
  },
  /**加载商品类的配置项参数 */
  getWholesaleConfig() {
    var that = this;
    var fkid = app.dns.proprietorId;
    var fkflag = app.dns.proprietor;
    list.getWholesaleConfigs(
      fkid,
      fkflag,
      (content)=> {
        that.setData({
          quantityDigits: content.QuantityDigits,
          priceDigits: content.PriceDigits,
          enableZeroStockBuy: content.EnableZeroStockBuy,
          NotShowProductNoneOffered: content.NotShowProductNoneOffered, // 是否不显示无货商品按钮
          spectStyle: content.GoodsDisplayMode,
          isScanty: content.IsScanty, //是否允许缺货登记
          decimalDigits: content.DecimalDigits,
          GoodsUnitDisplayMode: content.GoodsUnitDisplayMode,
          FrontShowStockDetail: content.FrontShowStockDetail
        });        
        that.productlist.setData({
          quantityDigits: content.QuantityDigits,
          priceDigits: content.PriceDigits,
          enableZeroStockBuy: content.EnableZeroStockBuy,
          NotShowProductNoneOffered: content.NotShowProductNoneOffered, // 是否不显示无货商品按钮
          showRetailPrice: content.ShowRetailPrice,
          spectStyle: content.GoodsDisplayMode,
          addressAssignDepot: content.AddressAssignDepot,
          GoodsUnitDisplayMode: content.GoodsUnitDisplayMode,
          FrontShowStockDetail: content.FrontShowStockDetail,
          isScanty: content.IsScanty //是否允许缺货登记
        });
        var is_search = true;
        //判断前当登录是否是同一个人
        if (this.data.tabKey != "product_" + app.dns.proprietorId + "_" + this.data.fkId) {
          this.data.tabKey = "product_" + app.dns.proprietorId + "_" + this.data.fkId;
          is_search = false;
        }
        if (that.data.activeIndex == 0 || !is_search) {
            that.productlist.setData({
            is_search: is_search
            });
            that.productlist.loadMain();
            if (that.data.activeIndex == 0){
             // that.onWiresharkEven();
              return;
            }

        }
        //如果无需要加载，则更新数量
        if (is_search) {
          that.updateNum();
        }
        else {
          that.cleanList(that);
          that.loadList(false);
        }
        
      });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    //隐藏原生底部导航
    hideTabbar()
    var tabindex = app.getTabBarindex();
    this.setData({
      tabindex:tabindex
    })
    this.isCanVisit(()=>{
      let entity = authorize.getEntity();
      let fkId = 0;
      if (app.dns.fkId != app.dns.proprietorId && !entity){
  
      }
      if (entity) {
        fkId = entity.fkId;
      }
      this.data.fkId=fkId;
  
      // this.deliveryComponent.getDefaultAddress();
      //获得配置
      this.getWholesaleConfig();
      // this.getTakePhotoAuth();
      // cart.get_cart_count();
    })
    this.setData({
      Currency:api.Currency || '￥'
    })
  },
  isCanVisit(callback){
    let that = this;
    this.clearVisitTimer();
    this.data.visitTimer = setTimeout(()=>{
      if(api.isLoginVisit!=undefined){
        that.data.loopCount = 0;
        if ((app.dns.fkFlag != app.dns.proprietor && app.dns.fkId > 0 && app.dns.proprietorId == 0 && !authorize.isLogin('store')) || (api.isLoginVisit&&!authorize.isLogin('store'))) {
          authorize.redirect('store');
        }else{
          callback();
        }
      }else if (that.data.loopCount < 60) {
        that.data.loopCount++;
        that.isCanVisit(callback);
      }
    }, 100)
  },
  clearVisitTimer(){
    if (this.data.visitTimer!=null) {
      clearTimeout(this.data.visitTimer);
      this.data.visitTimer = null;
    }
  },
  /**
   * 更新数量
   */
  updateNum(){
    var that=this;
    var current = this.data.lists[this.data.activeIndex];
    if (current.time && GoodsNumCache.compareTime(current.time)) {
      for (var i = 0; i < current.list.length; i++) {
        current.list[i].CartCount = GoodsNumCache.getProductNum(current.list[i].ProductId, current.list[i].CartCount,current.list[i].IsSingle==1);
      }
      var list_key = "lists[" + that.data.activeIndex + "].list";
      that.setData({
        [list_key]: current.list,
      });
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    clearIncrement();
    this.data.loopCount = 0;
    this.clearVisitTimer();
  },
  
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    if (this.data.activeIndex == 4) return;
    wx.stopPullDownRefresh();
    if (this.data.activeIndex == 0) {
      this.productlist.onPullDownRefresh();
      return;
    }

    this.data.lists[this.data.activeIndex].page.PageIndex = 1;
    this.data.lists[this.data.activeIndex].list = [];
    this.loadList();
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function(e) {
    if (this.data.activeIndex == 0) {
      this.productlist.onReachBottom(e);
      return;
    }
    var current = this.data.lists[this.data.activeIndex];
    if (current.hasMoreData) {
      var index = this.data.lists[this.data.activeIndex].page.PageIndex;
      this.data.lists[this.data.activeIndex].page.PageIndex = index + 1;
      this.loadList();
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  /**
   * 输入事件
   */
  onInputEvent: function(e) {
    this.data.code = e.detail.value;
  },
  /**
   * 根据code搜索商品
   */
  onSearchProductCodeEvent: function(e) {
    var that = this;
    if (!authorize.isLogin("store")) {
      util.tips("请先登录");
      authorize.redirect("store");
      return;
    }
    if (that.data.code.length == 0) {
      util.alert("请输入商品编码");
      return;
    }
    that.fasterComponent.setData({
      item: null,
      addCompleted:null,
      code: that.data.code,
      quantityDigits: that.data.quantityDigits, 
      priceDigits: that.data.priceDigits,
      isScanty: that.data.isScanty,
      areaCode: that.data.addr.code,
    });
    that.fasterComponent.onSearchProductCode(e);
  },
  /**
   * 表单值绑定
   */
  bindFormValue: function(e) {
    e = e.detail;
    this.data[e.target.id] = e.detail.value;

  },
  /**
   * 隐藏遮罩层
   */
  hideModal: function() {
    dialog.hideModal(this, 'showModalStatus')
  },
  /**
   * 清除每一列
   */
  cleanList: function(that) {
    for (var i = 0; i < that.data.lists.length-1; i++) {
      if(that.data.lists[i].list){
        that.data.lists[i].list = [];
        that.data.lists[i].page.PageIndex = 1;
      }
    }
    that.setData({
      lists: that.data.lists
    });
  },
  onPageScroll: function (e) {
    if (!this.productlist) return;
    if (this.scroll_timeout) {
      clearTimeout(this.scroll_timeout);
    }
    let scrollTop = e.scrollTop;
    this.scroll_timeout = setTimeout(()=>{
      this.productlist.setScollTop(scrollTop)
    }, 50);
  },
  /**
   * 页面滚动到
   */
  onPageScrollTo(e){
    
    wx.pageScrollTo({
      scrollTop: e.detail.scrollTop,
      duration: 0
    })  
  },
  //添加商品
  addGoods(e){
    console.log(e.detail,'------');
    // goodsList
    var pages = getCurrentPages(); //当前页面
    var prevPage = pages[pages.length - 2]; //上一页面
    prevPage.setData({
      //直接给上一个页面赋值
      uploadShopList: e.detail
    });
    wx.navigateBack({
      delta: 1
    })
  },
})